export default {
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || []
    // cart: [
    //   {
    //     id: 1,
    //     title: '商品标题',
    //     img: '图片',
    //     price: 99.99,
    //     amount: 2,
    //     desc: '商品描述信息',
    //     checked: true
    //   }
    // ]
  },
  mutations: {
    addItemToCart(state, payload) {
      const has = state.cart.some(prod => prod.id === payload.id)
      if (has) {
        state.cart = state.cart.map(prod => {
          if (prod.id === payload.id) {
            prod.amount += payload.amount
          }
          return prod
        })
      } else {
        state.cart = [
          ...state.cart,
          payload
        ]
      }
    },
    changeCartItemAmount(state, payload) {
      state.cart = state.cart.map(prod => {
        if (prod.id === payload.id) {
          prod.amount = payload.amount
        }
        return prod
      })
    },
    /**
     * 单选按钮状态
     */
    toggleCartItem(state, payload) {
      state.cart = state.cart.map(prod => {
        if (prod.id === payload) {
          prod.checked = !prod.checked
        }
        return prod
      })
    },
    toggleAllCart(state, payload) {
      state.cart = state.cart.map(prod => {
        prod.checked = payload
        return prod
      })
    },
    deletedItemCart(state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload)
    }
  },
  actions: {},
  getters: {
    TotalCount(state) {
      return state.cart.reduce((sum, curr) => {
        sum += curr.amount
        return sum
      }, 0)
    },
    getAll(state) {
      return state.cart.every(prod => prod.checked)
    },
    totalPrice(state) {
      return state.cart.reduce((total, prod) => {
        if (prod.checked) {
          total += prod.amount * prod.price
        }
        return total
      }, 0) * 100
    }
  }
}
